<?php

namespace ali;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use think\facade\Log;

// 阿里短信发送类
class Sms extends Client
{
    private const OK_SUCCESS = 'OK';

    /**
     * 短信发送-验证码
     * @param $phone
     * @param $code
     * @return bool
     */
    public static function sendCode($phone, $code, $key='sms')
    {
        $param = [
            'code' => $code,
        ];
        return self::sendSms($phone, $param, $key);
    }

    /**
     * 短信发送
     * @param $phone
     * @param $code
     * @return bool
     */
    public static function sendSms($phone, $param, $key='sms')
    {
        $config = self::getConfigSms($key);
        $signName = $config['signName'];
        $templateCode = $config['templateCode'];
        $sendSmsRequest = SendSmsRequest::fromMap([
            'PhoneNumbers' => $phone,
            'SignName' => $signName,
            'TemplateCode' => $templateCode,
            'TemplateParam' => json_encode($param, JSON_UNESCAPED_UNICODE),
        ]);
        $res = self::createClient()->sendSms($sendSmsRequest);
        $res = $res->toMap();
        $ok = $res['body']['Code'] ?? false;

        if($ok == self::OK_SUCCESS) {
            return true;
        }
        Log::error('短信发送失败');
        \Debug::setDebug($res['body']['Message'] ?? '短信发送失败');
        return false;
    }


}